package com.ht.oauthserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

// @EnableWebSecurity
// @EnableGlobalMethodSecurity(prePostEnabled = true)
/**
 *
 * 如果项目中包含 Spring Security 就会有 401 的问题，Spring Security 本身是通过 Filter
 * 实现的，如果没有对其单独做 CORS 的处理，在 Web Security 报错 401 的时候是不会返回相应的 CORS 的字段的。这会导致出现的
 * 401 错误成为了一个无法进行跨域的错误，导致前端程序无法正常的处理 401 相应 。对于spring security oauth2 默认接口，例如
 * /oauth/token 跨域问题，可以通过全局 CORS Filter 解决。
 */
/**
 * 自定义 CorsFilter，设置 order 优先级比 Spring Security 的 order 高。
 */
@Configuration
@Order(-1) // 优先级最高 解决前端访问跨域问题
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().anonymous().disable().requestMatchers().antMatchers("/**").and()
                .authorizeRequests().antMatchers("/oauth/**", "/login/**").permitAll().anyRequest().authenticated()
                .and().httpBasic();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        super.configure(web);
    }

    // 配置用户校验
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new PasswordEncoder() {

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return true;
            }

            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }
        }).withUser("test").password("test").authorities("USER");

    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    // 注入一个密码加密器
    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return true;
            }

            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }
        };
    }

}